

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/broswer.jpg">
  <link rel="icon" href="/img/broswer.jpg">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Feng Zikai">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. 遍历每一个数，判断是否是质数朴素方法 是否可以被整除我们判断$N$是否是质数时，不选要考虑$\leq N$的所有情况,只需要考虑$N$是否可以被小于等于$\sqrt{N}$的数整除就可以了，因此代码如下(此时不考虑并行情况) 123456789101112131415161718192021222324252627282930bool ifprime(int n)&amp;#123;    for">
<meta property="og:type" content="article">
<meta property="og:title" content="计算小于等于N的质数的并行算法">
<meta property="og:url" content="http://example.com/2022/03/17/%E8%AE%A1%E7%AE%97%E5%B0%8F%E4%BA%8E%E7%AD%89%E4%BA%8EN%E7%9A%84%E8%B4%A8%E6%95%B0%E7%9A%84%E5%B9%B6%E8%A1%8C%E7%AE%97%E6%B3%95/index.html">
<meta property="og:site_name" content="F7kyyy的博客">
<meta property="og:description" content="1. 遍历每一个数，判断是否是质数朴素方法 是否可以被整除我们判断$N$是否是质数时，不选要考虑$\leq N$的所有情况,只需要考虑$N$是否可以被小于等于$\sqrt{N}$的数整除就可以了，因此代码如下(此时不考虑并行情况) 123456789101112131415161718192021222324252627282930bool ifprime(int n)&amp;#123;    for">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/img/article/prime.jpg">
<meta property="article:published_time" content="2022-03-17T05:35:05.000Z">
<meta property="article:modified_time" content="2023-07-09T13:47:12.000Z">
<meta property="article:author" content="Feng Zikai">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="算法">
<meta property="article:tag" content="笔记">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/img/article/prime.jpg">
  
  
  
  <title>计算小于等于N的质数的并行算法 - F7kyyy的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  



  
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.5-a","typing":{"enable":true,"typeSpeed":60,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading1.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>F7kyyy&#39;s blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="计算小于等于N的质数的并行算法"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-03-17 13:35" pubdate>
          2022年3月17日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          3.6k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          30 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">计算小于等于N的质数的并行算法</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="1-遍历每一个数，判断是否是质数"><a href="#1-遍历每一个数，判断是否是质数" class="headerlink" title="1. 遍历每一个数，判断是否是质数"></a>1. 遍历每一个数，判断是否是质数</h2><h3 id="朴素方法-是否可以被整除"><a href="#朴素方法-是否可以被整除" class="headerlink" title="朴素方法 是否可以被整除"></a>朴素方法 是否可以被整除</h3><p>我们判断$N$是否是质数时，不选要考虑$\leq N$的所有情况,只需要考虑$N$是否可以被小于等于$\sqrt{N}$的数整除就可以了，因此代码如下(此时不考虑并行情况)</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-function"><span class="hljs-type">bool</span> <span class="hljs-title">ifprime</span><span class="hljs-params">(<span class="hljs-type">int</span> n)</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> k = <span class="hljs-number">2</span>; k &lt;= <span class="hljs-built_in">sqrt</span>(n); k++)<br>    &#123;<br>        <span class="hljs-keyword">if</span> (n % k == <span class="hljs-number">0</span>)<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">getPrime</span><span class="hljs-params">(vector&lt;<span class="hljs-type">long</span>&gt; &amp;prime)</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">2</span>; i &lt;= SIZE; i++)<br>    &#123;<br>        <span class="hljs-keyword">if</span> (ifprime(i))<br>            prime.<span class="hljs-built_in">emplace_back</span>(i);<br>    &#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span><br><span class="hljs-function"></span>&#123;<br>    vector&lt;<span class="hljs-type">long</span>&gt; prime;<br>    <span class="hljs-type">double</span> t = <span class="hljs-built_in">omp_get_wtime</span>();<br>    <span class="hljs-comment">// add your codes begin</span><br>    <span class="hljs-built_in">getPrime</span>(prime);<br>    <span class="hljs-comment">// add your codes end</span><br>    t = <span class="hljs-built_in">omp_get_wtime</span>() - t;<br>    <span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;time %f %ld\n&quot;</span>, t, <span class="hljs-built_in">long</span>(SIZE));<br>    <span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;\nsize %ld\n&quot;</span>, prime.<span class="hljs-built_in">size</span>());<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>此时运行时间为</strong></p>
<blockquote>
<p>time&#x3D;0.477831</p>
</blockquote>
<p>时间后的1000000时参数SIZE，含义是$\leq 1000000$中有78498个质数</p>
<p><img src="https://cdn.jsdelivr.net/gh/F7kyyy/picture@main/img/202203261347360.png" srcset="/img/loading1.gif" lazyload alt="202203171647230"></p>
<p>而在使用openmp并行后，从2-SIZE，每个线程分配一部分，判断是否为质数。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-function"><span class="hljs-type">bool</span> <span class="hljs-title">ifprime</span><span class="hljs-params">(<span class="hljs-type">int</span> n)</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> k = <span class="hljs-number">2</span>; k &lt;= <span class="hljs-built_in">sqrt</span>(n); k++)<br>    &#123;<br>        <span class="hljs-keyword">if</span> (n % k == <span class="hljs-number">0</span>)<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">getPrime</span><span class="hljs-params">(vector&lt;<span class="hljs-type">long</span>&gt; &amp;prime)</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-comment">// 并行的写入vector</span><br><span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp parallel</span><br>    &#123;<br>        vector&lt;<span class="hljs-type">int</span>&gt; vec_private;<br><span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp for nowait schedule(static)</span><br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">2</span>; i &lt;= SIZE; i++)<br>        &#123;<br>            <span class="hljs-keyword">if</span> (ifprime(i))<br>                vec_private.<span class="hljs-built_in">emplace_back</span>(i);<br>        &#125;<br><span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp critical</span><br>        prime.<span class="hljs-built_in">insert</span>(prime.<span class="hljs-built_in">end</span>(), vec_private.<span class="hljs-built_in">begin</span>(), vec_private.<span class="hljs-built_in">end</span>());<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>此时运行时间为</strong></p>
<blockquote>
<p>time&#x3D;0.033235</p>
</blockquote>
<p><img src="https://cdn.jsdelivr.net/gh/F7kyyy/picture@main/img/202203261348208.png" srcset="/img/loading1.gif" lazyload alt="202203171651834"></p>
<h3 id="优化判断质数函数"><a href="#优化判断质数函数" class="headerlink" title="优化判断质数函数"></a>优化判断质数函数</h3><p>首先，我们应该知道一个关于质数分布的规律：<strong>大于等于5的质数一定和6的倍数相邻</strong>。例如5和7，11和13,17和19,<strong>反之是不一定成立的</strong></p>
<p>证明：令x≥1，将大于等于5的自然数表示如下：··· 6x-1，6x，6x+1，6x+2，6x+3，6x+4，6x+5，6(x+1），6(x+1)+1 ···</p>
<p>可以看到，不和6的倍数相邻的数为6x+2，6x+3，6x+4，由于2(3x+1)，3(2x+1)，2(3x+2)，所以它们一定不是素数，再除去6x本身，显然，素数要出现只可能出现在6x的相邻两侧。因此在5到$\sqrt{n}$中每6个数只判断2个，时间复杂度O($\frac{\sqrt{n}}{3}$),C++代码如下</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-function"><span class="hljs-type">bool</span> <span class="hljs-title">ifprime</span><span class="hljs-params">(<span class="hljs-type">int</span> n)</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">if</span> (n == <span class="hljs-number">2</span> || n == <span class="hljs-number">3</span>)<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    <span class="hljs-keyword">if</span> (n % <span class="hljs-number">6</span> != <span class="hljs-number">1</span> &amp;&amp; n % <span class="hljs-number">6</span> != <span class="hljs-number">5</span>)<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> k = <span class="hljs-number">5</span>; k &lt;= <span class="hljs-built_in">floor</span>(<span class="hljs-built_in">sqrt</span>(n)); k += <span class="hljs-number">6</span>)<br>        <span class="hljs-keyword">if</span> (n % k == <span class="hljs-number">0</span> || n % (k + <span class="hljs-number">2</span>) == <span class="hljs-number">0</span>)<br>            <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>串行 <strong>此时运行时间为</strong></p>
<blockquote>
<p>time&#x3D;0.156363</p>
</blockquote>
<p><img src="https://cdn.jsdelivr.net/gh/F7kyyy/picture@main/img/202203261348573.png" srcset="/img/loading1.gif" lazyload alt="202203171659060"></p>
<p>并行 <strong>此时运行时间为</strong></p>
<blockquote>
<p>time&#x3D;0.015401</p>
</blockquote>
<p><img src="https://cdn.jsdelivr.net/gh/F7kyyy/picture@main/img/202203261348471.png" srcset="/img/loading1.gif" lazyload alt="202203171713716"></p>
<h2 id="2-使用筛法"><a href="#2-使用筛法" class="headerlink" title="2. 使用筛法"></a>2. 使用筛法</h2><p>我们可以标记所有合数，然后求质数</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-type">long</span> sign[SIZE + <span class="hljs-number">1</span>];<br><br><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">getPrime</span><span class="hljs-params">(vector&lt;<span class="hljs-type">long</span>&gt; &amp;prime)</span></span><br><span class="hljs-function"></span>&#123;<br>  <span class="hljs-type">int</span> N = <span class="hljs-built_in">sqrt</span>(SIZE);<br>  <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">2</span>; i &lt;= N; i++)<br>  &#123;<br>    <span class="hljs-keyword">if</span> (!sign[i])<br>      <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> j = i; j &lt;= SIZE / i; j++)<br>        sign[i * j] = <span class="hljs-literal">true</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>sign[i]&#x3D;true表示i为合数，当一个数i是质数时，我们标记$i<em>j$为合数，$i</em>j\leq SIZE$</p>
<h3 id="串行"><a href="#串行" class="headerlink" title="串行"></a>串行</h3><p><strong>此时运行时间为</strong></p>
<blockquote>
<p>time&#x3D;0.021131</p>
</blockquote>
<p><img src="https://cdn.jsdelivr.net/gh/F7kyyy/picture@main/img/202203261349127.png" srcset="/img/loading1.gif" lazyload alt="202203171712942"></p>
<h3 id="在遍历时并行"><a href="#在遍历时并行" class="headerlink" title="在遍历时并行"></a>在遍历时并行</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs c++">  <span class="hljs-type">int</span> N = <span class="hljs-built_in">sqrt</span>(SIZE);<br>  <span class="hljs-comment">// 并行的使用筛法找出所有合数</span><br><span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp parallel for num_threads(NUM_THREADS)</span><br>  <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">2</span>; i &lt;= N; i++)<br>  &#123;<br>    <span class="hljs-keyword">if</span> (!sign[i])<br>      <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> j = i; j &lt;= SIZE / i; j++)<br>        sign[i * j] = <span class="hljs-literal">true</span>;<br>  &#125;<br></code></pre></td></tr></table></figure>

<p><strong>此时运行时间为</strong></p>
<blockquote>
<p>time&#x3D;0.012204</p>
</blockquote>
<p><img src="https://cdn.jsdelivr.net/gh/F7kyyy/picture@main/img/202203261349515.png" srcset="/img/loading1.gif" lazyload alt="202203171716363"></p>
<h3 id="在寻找合数时并行"><a href="#在寻找合数时并行" class="headerlink" title="在寻找合数时并行"></a>在寻找合数时并行</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs c++">  <span class="hljs-type">int</span> N = <span class="hljs-built_in">sqrt</span>(SIZE);<br><span class="hljs-comment">// 并行的使用筛法找出所有合数</span><br>  <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">2</span>; i &lt;= N; i++)<br>  &#123;<br>    <span class="hljs-keyword">if</span> (!sign[i])<br>    <span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp parallel for num_threads(NUM_THREADS)</span><br>      <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> j = i; j &lt;= SIZE / i; j++)<br>        sign[i * j] = <span class="hljs-literal">true</span>;<br>  &#125;<br></code></pre></td></tr></table></figure>

<p><strong>此时运行时间为</strong></p>
<blockquote>
<p>time&#x3D;0.006109</p>
</blockquote>
<p><img src="https://cdn.jsdelivr.net/gh/F7kyyy/picture@main/img/202203261349256.png" srcset="/img/loading1.gif" lazyload alt="202203171718941"></p>
<h2 id="3-时间对比"><a href="#3-时间对比" class="headerlink" title="3. 时间对比"></a>3. 时间对比</h2><table>
<thead>
<tr>
<th>方法</th>
<th>时间</th>
</tr>
</thead>
<tbody><tr>
<td>朴素方法 串行</td>
<td>0.477831</td>
</tr>
<tr>
<td>朴素方法 并行</td>
<td>0.033235</td>
</tr>
<tr>
<td>优化判断质数 串行</td>
<td>0.156363</td>
</tr>
<tr>
<td>优化判断质数 并行</td>
<td>0.015401</td>
</tr>
<tr>
<td>筛法 串行</td>
<td>0.021131</td>
</tr>
<tr>
<td>筛法 遍历时并行</td>
<td>0.012204</td>
</tr>
<tr>
<td>筛法 寻找合数时并行</td>
<td>0.006109</td>
</tr>
</tbody></table>
<h2 id="4-多线程写入vector"><a href="#4-多线程写入vector" class="headerlink" title="4. 多线程写入vector"></a>4. 多线程写入vector</h2><p>在完成上述问题时，遇到过循环中多线程无法对同一个vector进行写操作，有以下几种解决方法</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs c++">std::vector&lt;<span class="hljs-type">int</span>&gt; vec;<br><span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp parallel</span><br>&#123;<br>    std::vector&lt;<span class="hljs-type">int</span>&gt; vec_private;<br>    <span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp for nowait <span class="hljs-comment">//fill vec_private in parallel</span></span><br>    <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-number">100</span>; i++) &#123;<br>        vec_private.<span class="hljs-built_in">push_back</span>(i);<br>    &#125;<br>    <span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp critical</span><br>    vec.<span class="hljs-built_in">insert</span>(vec.<span class="hljs-built_in">end</span>(), vec_private.<span class="hljs-built_in">begin</span>(), vec_private.<span class="hljs-built_in">end</span>());<br>&#125;<br></code></pre></td></tr></table></figure>

<p>OpenMP 4.0允许使用reduction</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp declare reduction (merge : std::vector<span class="hljs-string">&lt;int&gt;</span> : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end()))</span><br><br>std::vector&lt;<span class="hljs-type">int</span>&gt; vec;<br><span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp parallel for reduction(merge: vec)</span><br><span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-number">100</span>; i++) <br>    vec.<span class="hljs-built_in">push_back</span>(i);<br></code></pre></td></tr></table></figure>

<p>较为详细的可以这样</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs c++">std::vector&lt;<span class="hljs-type">int</span>&gt; vec;<br><span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp parallel</span><br>&#123;<br>    std::vector&lt;<span class="hljs-type">int</span>&gt; vec_private;<br>    <span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp for nowait schedule(static)</span><br>    <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>; i&lt;N; i++) &#123; <br>        vec_private.<span class="hljs-built_in">push_back</span>(i);<br>    &#125;<br>    <span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp for schedule(static) ordered</span><br>    <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-built_in">omp_get_num_threads</span>(); i++) &#123;<br>        <span class="hljs-meta">#<span class="hljs-keyword">pragma</span> omp ordered</span><br>        vec.<span class="hljs-built_in">insert</span>(vec.<span class="hljs-built_in">end</span>(), vec_private.<span class="hljs-built_in">begin</span>(), vec_private.<span class="hljs-built_in">end</span>());<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>


                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%B9%B6%E8%A1%8C%E8%AE%A1%E7%AE%97/" class="category-chain-item">并行计算</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/C/" class="print-no-link">#C++</a>
      
        <a href="/tags/%E7%AE%97%E6%B3%95/" class="print-no-link">#算法</a>
      
        <a href="/tags/%E7%AC%94%E8%AE%B0/" class="print-no-link">#笔记</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>计算小于等于N的质数的并行算法</div>
      <div>http://example.com/2022/03/17/计算小于等于N的质数的并行算法/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Feng Zikai</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年3月17日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/03/17/fluid%E4%B8%BB%E9%A2%98%E4%BC%98%E5%8C%96/" title="fluid主题优化">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">fluid主题优化</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/03/13/%E4%BA%91%E8%AE%A1%E7%AE%97%E4%BD%9C%E4%B8%9A1/" title="云计算作业1">
                        <span class="hidden-mobile">云计算作业1</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数...</span> <span id="times">载入时分秒...</span> <script src="/js/duration.js"></script> </div> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>




  
<script src="//cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script>
<script src="//cdn.jsdelivr.net/gh/metowolf/Metingjs@1.2/dist/Meting.min.js"></script>
<script src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
